package com.flats.webview;

import com.flats.model.entity.Address;
import com.flats.model.entity.Users;
import com.flats.service.transactional.TransactionalAddressService;
import com.flats.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.Set;
import java.util.TreeSet;

@Controller
public class SearchController {
    @Autowired
    TransactionalAddressService addressService;

    @RequestMapping(value = "/country")
    public
    @ResponseBody
    Set<String> country(Model model, @RequestParam(value = "country") String country) {
        Set<String> citiesList = new TreeSet<String>();
        Utils.setSession(Constants.COUNTRY, country);
        for (Address address : addressService.getAll()) {
            if (country.equals(address.getCountry())) {
                citiesList.add(address.getCity());
            }
        }
        Utils.setSession(Constants.CITIES,citiesList);
        return citiesList;
//        return Utils.GSON.toJson(addressService.getAll());
    }

    @RequestMapping(value = "/city")
    public
    @ResponseBody
    Set<String> city(Model model, @RequestParam(value = "city") String city) {
        Utils.setSession(Constants.CITY, city);
        Set<String> streetList = new TreeSet<String>();
        for (Address address : addressService.getAll()) {
            if (city.equals(address.getCity())) {
                streetList.add(address.getStreet());
            }
        }
        Utils.setSession(Constants.STREETS,streetList);
        return streetList;
    }

    @RequestMapping(value = "/street")
    public
    @ResponseBody
    void street(Model model, @RequestParam(value = "street") String street) {
        Utils.setSession(Constants.STREET, street);
    }
    @RequestMapping(value = "/searchModel")
    public @ResponseBody void searchModel(Model model) {
        Set<String> countries = (Set<String>) Utils.getSession(Constants.COUNTRIES);
        model.addAttribute("countryListSess",countries);
        Set<String> cities = (Set<String>) Utils.getSession(Constants.CITIES);
        model.addAttribute("citiesListSess",cities);
        Set<String> streets = (Set<String>) Utils.getSession(Constants.STREETS);
        model.addAttribute("streetsListSess",streets);
    }

}
